import uuid

from fastapi import HTTPException
from sqlalchemy.orm import Session

from api.model.knowledgebase_model import Knowledgebase
from api.utils.session import with_session
from api.vo.form.knowledge_form import KnowledgebaseForm
from api.vo.query.knowledgebase_query import KnowledgebaseQuery
from api.vo.value.knowledgebase_value import KnowledgebaseValue


@with_session
def add(session: Session, knowledge: Knowledgebase):
    knowledge.id = str(uuid.uuid4())
    session.add(knowledge)
    return knowledge

@with_session
def list(session: Session,knowledgebase: KnowledgebaseQuery):
    query = session.query(Knowledgebase)
    if knowledgebase.name:
        query = query.filter(Knowledgebase.name.like(f"%{knowledgebase.name}%"))
    query = query.order_by(Knowledgebase.create_date.desc()).limit(knowledgebase.rows).offset((knowledgebase.page - 1) * knowledgebase.rows)
    knowledgebases = query.all()
    count = query.count()
    if not knowledgebases:
        return []
    list = [
        KnowledgebaseValue(id=el.id,
           name=el.name,
           description=el.description,
           docNum=el.doc_num,
           createdTime=el.create_date.strftime("%Y-%m-%d %H:%M:%S")
        ) for el in knowledgebases
    ]
    return list, count

@with_session
def update(session: Session, knowledgeForm: KnowledgebaseForm):
    knowledge = session.get(Knowledgebase, knowledgeForm.id)
    knowledge.name = knowledgeForm.name
    knowledge.description = knowledgeForm.description
    session.merge(knowledge)
    return knowledge

@with_session
def delete(session: Session, idList: list):
    for id in idList:
        knowledge = session.get(Knowledgebase, id)
        if not knowledge:
            raise HTTPException(status_code=404, detail=f"id={id}的模型不存在")
        session.delete(knowledge)
    return idList
@with_session
def update_status(session: Session, idList: list, status: str):
    for id in idList:
        knowledge = session.get(Knowledgebase, id)
        if not knowledge:
            raise HTTPException(status_code=404, detail=f"id={id}的模型不存在")
        knowledge.status = status
        session.merge(knowledge)
    return idList


@with_session
def exist(session: Session, name: str, id: str):
    if id:
        data = session.get(Knowledgebase, id)
        if data.name == name:
            return False
    data = session.query(Knowledgebase).filter(Knowledgebase.name == name).first()
    if data:
        return True
    return False


@with_session
def get(session: Session, id: str):
    el = session.get(Knowledgebase, id)
    return KnowledgebaseValue(
        id=el.id,
        name=el.name,
        description=el.description,
        docNum=el.doc_num,
        createdTime=el.create_date.strftime("%Y-%m-%d %H:%M:%S")
   )